package org.bookr.console.controller;

import org.bookr.engine.model.Administrator;
import org.bookr.engine.service.BookrService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ValidationUtils;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author Pawel Tomaszewski
 */
@Controller
public class AdministratorController {
    private Logger logger = LoggerFactory.getLogger(AdministratorController.class);
    private BookrService bookrService;

    @RequestMapping(value = "/administrator/create", method = RequestMethod.GET)
    public ModelAndView createAdministratorForm() {
        ModelAndView result = new ModelAndView("console.createAdministrator");
        result.addObject("status", "console.webapp.status.fillForm");
        result.addObject("administrator", new Administrator());
        return result;
    }

    @RequestMapping(value = "/administrator/create", method = RequestMethod.POST)
    public ModelAndView processCreateAdministratorForm(@ModelAttribute Administrator administrator, BindingResult bindingResult) {
        ModelAndView results = new ModelAndView("console.createAdministrator");
        ValidationUtils.rejectIfEmptyOrWhitespace(bindingResult, "firstName", "console.webapp.formValidation.emptyField");
        ValidationUtils.rejectIfEmptyOrWhitespace(bindingResult, "lastName", "console.webapp.formValidation.emptyField");
        ValidationUtils.rejectIfEmptyOrWhitespace(bindingResult, "username", "console.webapp.formValidation.emptyField");
        ValidationUtils.rejectIfEmptyOrWhitespace(bindingResult, "password", "console.webapp.formValidation.emptyField");
        if(bindingResult.hasErrors()) {
            results.addObject("status", "console.webapp.status.correctForm");
            logger.debug("creating administrator failed, errors: " + bindingResult.getErrorCount());
        } else {
            Date now = new Date();
            administrator.setCreatedDate(now);
            administrator.setLastUpdateDate(now);
            String id = bookrService.updateAdministrator(administrator);
            results.addObject("status", "console.webapp.status.createSuccess");
            results.addObject("administrator", bookrService.loadAdministratorById(id));
            results.setViewName("console.administrator");
            logger.debug("administrator created successfully");
        }
        return results;
    }

    @RequestMapping(value = "/administrator/{id}/edit", method = RequestMethod.GET)
    public ModelAndView editAdministratorForm(@PathVariable String id) {
        ModelAndView results = new ModelAndView("console.editAdministrator");
        results.addObject("status", "console.webapp.status.fillForm");
        results.addObject("administrator", bookrService.loadAdministratorById(id));
        return results;
    }

    @RequestMapping(value = "/administrator/{id}/edit", method = RequestMethod.POST)
    public ModelAndView processEditAdministratorForm(@PathVariable String id,
                                                     @ModelAttribute Administrator administrator, BindingResult bindingResult) {
        ModelAndView results = new ModelAndView("console.editAdministrator");
        ValidationUtils.rejectIfEmptyOrWhitespace(bindingResult, "firstName", "console.webapp.formValidation.emptyField");
        ValidationUtils.rejectIfEmptyOrWhitespace(bindingResult, "lastName", "console.webapp.formValidation.emptyField");
        ValidationUtils.rejectIfEmptyOrWhitespace(bindingResult, "username", "console.webapp.formValidation.emptyField");
        ValidationUtils.rejectIfEmptyOrWhitespace(bindingResult, "password", "console.webapp.formValidation.emptyField");
        if(bindingResult.hasErrors()) {
            results.addObject("status", "console.webapp.status.correctForm");
            logger.debug("There are some errors in form: " + bindingResult.getErrorCount());
        } else {
            results.addObject("status", "console.webapp.status.editSuccess");
            results.addObject("administrator", bookrService.loadAdministratorById(id));
            results.setViewName("console.administrator");
            administrator.setLastUpdateDate(new Date());
            bookrService.updateAdministrator(administrator);
            logger.debug("Administrator successfully saved!");
        }
        return results;
    }

    @RequestMapping("/administrators")
    public ModelAndView listAdministrators() {
        ModelAndView results = new ModelAndView("console.administrators");
        results.addObject("status", "console.webapp.status.ok");
        results.addObject("administrators", bookrService.listAdministrators());
        return results;
    }

    @RequestMapping(value = "/administrator/{id}")
    public ModelAndView showAdministrator(@PathVariable String id) {
        ModelAndView results = new ModelAndView("console.administrator");
        results.addObject("status", "console.webapp.status.ok");
        results.addObject("administrator", bookrService.loadAdministratorById(id));
        return results;
    }

    @RequestMapping("/administrator/{id}/remove")
    public ModelAndView removeAdministrator(@PathVariable String id) {
        ModelAndView results = new ModelAndView("redirect:/administrators");
        bookrService.removeAdministrator(bookrService.loadAdministratorById(id));
        return results;
    }

    @InitBinder
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy.MM.dd 'at' HH:mm:ss");
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
    }

    public BookrService getBookrService() {
        return bookrService;
    }

    public void setBookrService(BookrService bookrService) {
        this.bookrService = bookrService;
    }
}
